


package com.wanchuang.shengfubao.module.main;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.viewpager.widget.ViewPager;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.chaychan.viewlib.NumberRunningTextView;
import com.google.protobuf.InvalidProtocolBufferException;
import com.wanchuang.shengfubao.R;
import com.wanchuang.shengfubao.adapter.ViewPagerAdapter;
import com.wanchuang.shengfubao.base.BaseFragment;
import com.wanchuang.shengfubao.module.account.AccountActivity;
import com.wanchuang.shengfubao.module.allow.AllowApplyActivity;
import com.wanchuang.shengfubao.module.machines.AllowActivity;
import com.wanchuang.shengfubao.module.machines.AllowBackActivity;
import com.wanchuang.shengfubao.module.machines.MachinesActivity;
import com.wanchuang.shengfubao.module.partner.PartnerActivity;
import com.wanchuang.shengfubao.module.policy.PolicyOneActivity;
import com.wanchuang.shengfubao.module.policy.PolicyThreeActivity;
import com.wanchuang.shengfubao.module.policy.PolicyTwoActivity;
import com.wanchuang.shengfubao.module.shop.ShopActivity;
import com.wanchuang.shengfubao.net.Apis;
import com.wanchuang.shengfubao.net.NetworkManager;
import com.wanchuang.shengfubao.net.WebApis;
import com.wanchuang.shengfubao.net.interfaces.OnRequestCallBack;
import com.wanchuang.shengfubao.proto.Index;
import com.wanchuang.shengfubao.proto.MemberOuterClass;
import com.wanchuang.shengfubao.proto.Recharge;
import com.wanchuang.shengfubao.view.BannerImageHoderView;
import com.wanchuang.shengfubao.view.MyScrollview;
import com.wanchuang.shengfubao.web.ui.WebViewActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/2/2 0002.
 */

public class HomeFragment extends BaseFragment implements View.OnClickListener {


    private Unbinder unbinder;

    @BindView(R.id.tv_member_name)
    TextView tvMemberName;
    @BindView(R.id.scrollview)
    MyScrollview scrollview;
    @BindView(R.id.rv_title)
    LinearLayout rvTitle;
    @BindView(R.id.category_page)
    ViewPager category_viewPager;
    @BindView(R.id.ll_dot)
    LinearLayout mLlDot;
    @BindView(R.id.home_convenient_banner)
    ConvenientBanner convenientBanner;
    @BindView(R.id.tv_marquess)
    TextView tvMarquess;
    @BindView(R.id.minus)
    TextView minus;
    @BindView(R.id.home_today_income)
    NumberRunningTextView home_today_income;
    @BindView(R.id.home_today_trad)
    NumberRunningTextView home_today_trad;
    @BindView(R.id.home_today_fazan)
    NumberRunningTextView home_today_fazan;
    @BindView(R.id.home_today_action)
    NumberRunningTextView home_today_action;


    private List<Index.get_show_list.List> advDatas;
    private ArrayList<Recharge.today_earnings.Earningsinfo.List> mData = new ArrayList<>();


    private List<View> categoryViews;
    private View category_viewOne;
    private View category_viewTwo;

    /**
     * 当前显示的是第几页
     */
    private int curIndex = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void initView() {
        initCategory();

    }

    private void initCategory() {
        LayoutInflater mInflater = LayoutInflater.from(mContext);
        categoryViews = new ArrayList<>();
        category_viewOne = mInflater.inflate(R.layout.home_category_layout, null);
        category_viewTwo = mInflater.inflate(R.layout.home_category_layout_next, null);
        categoryViews.add(category_viewOne);
        categoryViews.add(category_viewTwo);
        ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(categoryViews);
        category_viewPager.setAdapter(pagerAdapter);
        category_viewPager.setCurrentItem(curIndex);
        category_viewPager.setOffscreenPageLimit(2);
        category_viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                // 取消圆点选中
                mLlDot.getChildAt(curIndex)
                        .findViewById(R.id.v_dot)
                        .setBackgroundResource(R.mipmap.dot_normal);
                // 圆点选中
                mLlDot.getChildAt(position)
                        .findViewById(R.id.v_dot)
                        .setBackgroundResource(R.mipmap.dot_selected);
                curIndex = position;

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        for (int i = 0; i < categoryViews.size(); i++) {
            mLlDot.addView(mInflater.inflate(R.layout.dot, null));
        }
        // 默认显示第一页
        mLlDot.getChildAt(0).findViewById(R.id.v_dot)
                .setBackgroundResource(R.mipmap.dot_selected);
        category_viewOne.findViewById(R.id.home_category_one).setOnClickListener(this);
        category_viewOne.findViewById(R.id.home_category_two).setOnClickListener(this);
        category_viewOne.findViewById(R.id.home_category_three).setOnClickListener(this);
        category_viewOne.findViewById(R.id.home_category_four).setOnClickListener(this);
        category_viewOne.findViewById(R.id.home_category_five).setOnClickListener(this);
        category_viewOne.findViewById(R.id.home_category_six).setOnClickListener(this);
        category_viewOne.findViewById(R.id.home_category_seven).setOnClickListener(this);
        category_viewOne.findViewById(R.id.home_category_eight).setOnClickListener(this);
        category_viewTwo.findViewById(R.id.home_category_nine).setOnClickListener(this);
        category_viewTwo.findViewById(R.id.home_category_ten).setOnClickListener(this);
        category_viewTwo.findViewById(R.id.home_category_eleven).setOnClickListener(this);
        category_viewTwo.findViewById(R.id.home_category_tweleve).setOnClickListener(this);
        tvMarquess.setOnClickListener(this);
    }

    private void initEarnView() {

    }

    private void loadEarn() {
        NetworkManager.INSTANCE.post(Apis.today_earnings, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                Recharge.today_earnings datas = Recharge.today_earnings.parseFrom(bytes);
                mData.clear();
                mData.addAll(datas.getEarningsInfo().getListList());
                if (mData.size() >= 4) {
                    if (mData.get(0).getToday().contains("-")) {
                        minus.setVisibility(View.VISIBLE);
                    } else {
                        minus.setVisibility(View.GONE);
                    }
                    home_today_income.setContent(mData.get(0).getToday());
                    home_today_trad.setContent(mData.get(1).getToday());
                    home_today_action.setContent(mData.get(2).getToday());
                    home_today_fazan.setContent(mData.get(3).getToday());
                }
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
            }
        });
    }


    /**
     * 加载数据项
     */
    private void initBottomBanner() {
        // 加载banner的数据
        Index.get_show_list.Builder builder = Index.get_show_list.newBuilder();
        builder.setType("1");
        NetworkManager.INSTANCE.post(Apis.get_banner, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                Index.get_show_list data = Index.get_show_list.parseFrom(bytes);
                advDatas = data.getAdvListList();
                convenientBanner.setPages(new CBViewHolderCreator() {
                    @Override
                    public BannerImageHoderView createHolder(View itemView) {
                        return new BannerImageHoderView(itemView, mContext);
                    }

                    @Override
                    public int getLayoutId() {
                        return R.layout.item_localimage;
                    }
                }, advDatas);
                convenientBanner.startTurning(6000);
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                showToast(errorMessage);
            }
        });
    }

    private void loadMemberInfo() {
        NetworkManager.INSTANCE.post(Apis.memberDataInfo, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                MemberOuterClass.Member member = MemberOuterClass.Member.parseFrom(bytes);
                if (TextUtils.isEmpty(member.getMemberName())) {
                    tvMemberName.setText(member.getTruename());
                } else {
                    tvMemberName.setText(member.getMemberName());
                }

            }

            @Override
            public void onError(int code, String errorMessage) {

            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        initBottomBanner();
        loadEarn();
        loadMemberInfo();
        setMarqueeText();
    }


    @Override
    protected void init() {
    }


    private void setMarqueeText() {
        tvMarquess.setEllipsize(TextUtils.TruncateAt.MARQUEE);
        tvMarquess.setSingleLine(true);
        tvMarquess.setSelected(true);
        tvMarquess.setFocusable(true);
        tvMarquess.setFocusableInTouchMode(true);
        NetworkManager.INSTANCE.post(Apis.system_log, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                MemberOuterClass.System_log data = MemberOuterClass.System_log.parseFrom(response);
                List<MemberOuterClass.System_log.System_log_list> lists = data.getSystemLogListList();
                if (lists.size() > 0)
                    tvMarquess.setText(lists.get(0).getPushTitle() + " " + lists.get(0).getPushMessage());
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                tvMarquess.setText("暂无通知");
            }
        });


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.home_category_one:
                startActivity(AccountActivity.class);
                break;
            case R.id.home_category_two:
                startActivity(PartnerActivity.class);
                break;
            case R.id.home_category_three:
                startActivity(ShopActivity.class);
                break;
            case R.id.home_category_four:
                startActivity(MachinesActivity.class);
                break;
            case R.id.home_category_five:
                startActivity(AllowActivity.class);
                break;
            case R.id.home_category_six:
                startActivity(AllowApplyActivity.class);
                break;
            case R.id.home_category_seven:
                startActivity(AllowBackActivity.class);
                break;
            case R.id.home_category_eight:
                startActivity(PolicyOneActivity.class);
                break;
            case R.id.home_category_nine:
                startActivity(PolicyTwoActivity.class);
                break;
            case R.id.home_category_ten:
                startActivity(PolicyThreeActivity.class);
                break;
            case R.id.home_category_eleven:
                WebViewActivity.startActivity(mContext, WebApis.HandlingRecords);
                break;
            case R.id.home_category_tweleve:
                WebViewActivity.startActivity(mContext, WebApis.merchantAccess);
                break;
            case R.id.tv_marquess:
                startActivity(MessageActivity.class);
                break;

        }
    }
}
